package com.admin.rxandroidtest.retrofit;

import android.content.Context;

import com.admin.rxandroidtest.IRequstCode;
import com.admin.rxandroidtest.NetErrStringUtils;
import com.admin.rxandroidtest.RequestListener;

import retrofit2.Call;
import retrofit2.Callback;
import retrofit2.Response;
import retrofit2.Retrofit;
import retrofit2.converter.gson.GsonConverterFactory;

/**
 * Created by 吴昶 on 2018/8/15.
 */
public class RetrofitServer {

    private static RetrofitServer retrofitServer;
    private Retrofit retrofit;
    private Context context;

    /**
     * 单例 再 MyApplication 中初始化调用
     * 防止重复多次 新建对象
     * @return
     */
    public static RetrofitServer getInstance(){
        if(retrofitServer==null){
            retrofitServer=new RetrofitServer();
        }
        return retrofitServer;
    }

    /**
     * 初始化 Retrofit
     * @param context
     * @param url
     */
    public void init(Context context,String url){
        this.context=context;
        retrofit=new Retrofit.Builder()
                .baseUrl(url)
                .addConverterFactory(GsonConverterFactory.create())
                .build();
    }

    /**
     * 获取接口对象  本例中主要是 BlogServer
     * @param clazz
     * @param <T>
     * @return
     */
    public <T> T createCall(Class<T> clazz){
        return retrofit.create(clazz);
    }

    /**
     * 设置通用的数据请求方法
     * @param requestCall  call
     * @param requestCode  反馈码，自填
     * @param requestListener  数据获取的回调监听
     * @param <T>
     */
    public <T extends IRequstCode> void enqueue(Call<T> requestCall, final int requestCode, final RequestListener<T> requestListener){
        requestCall.enqueue(new Callback<T>() {
            @Override
            public void onResponse(Call<T> call, Response<T> response) {
                if(response.isSuccessful()) {
                    T result = response.body();
                    if (result == null) {
                        requestListener.onResquestError(requestCode,response.code(),"");
                        return;
                    }else {
                        requestListener.onResquestSuccess(result);
                    }
                }else {
                    requestListener.onResquestError(requestCode,response.code(), NetErrStringUtils.getErrString(context,response.code()));
                }

            }

            @Override
            public void onFailure(Call<T> call, Throwable t) {
                requestListener.onResquestError(requestCode,0,NetErrStringUtils.getErrString(context,t));
            }
        });
    };

}
